package com.supfunky.inspaquotes;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.*;
import com.facebook.android.Facebook;
import com.facebook.model.*;


public class MainActivity extends Activity {
	
    ArrayList<Integer> pics = new ArrayList<Integer>();
    LayoutInflater inflater;    //Used to create individual pages
    ViewPager vp;    //Reference to class to swipe views
    private PendingAction pendingAction = PendingAction.NONE;
    private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
    
    private enum PendingAction {
        NONE,
        POST_PHOTO,
        POST_STATUS_UPDATE
    }

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		
		setContentView(R.layout.activity_main);

		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);

        pics.add(R.drawable.inspa_1);
        pics.add(R.drawable.inspa_2);
        pics.add(R.drawable.inspa_3);
        pics.add(R.drawable.inspa_4);
        pics.add(R.drawable.inspa_5);
        pics.add(R.drawable.inspa_6);
        pics.add(R.drawable.inspa_7);
        pics.add(R.drawable.inspa_8);
        pics.add(R.drawable.inspa_9);
        pics.add(R.drawable.inspa_11);
		
		
        //get an inflater to be used to create single pages
        inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //Reference ViewPager defined in activity
        vp=(ViewPager)findViewById(R.id.viewPager);
        //set the adapter that will create the individual pages
        vp.setAdapter(new MyPagesAdapter());

        
        //Set up Facebook Button
        ImageButton button = (ImageButton)findViewById(R.id.facebookButton);
        button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				onClickPostPhoto();
			}
		});
        
        
        
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	
    //Implement PagerAdapter Class to handle individual page creation
    class MyPagesAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            //Return total pages, here one for each data item
            return pics.size();
        }
        //Create the given page (indicated by position)
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View page = inflater.inflate(R.layout.page, null);
            ((ImageView)page.findViewById(R.id.picView)).setImageResource(pics.get(position));
            //Add the page to the front of the queue
            ((ViewPager) container).addView(page, 0);
            return page;
        }
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            //See if object from instantiateItem is related to the given view
            //required by API
            return arg0==(View)arg1;
        }
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
          ((ViewPager) container).removeView((View) object);
          object=null;
        }

    }
    
    
    private void onClickPostPhoto() {
        performPublish(PendingAction.POST_PHOTO);
    }
    
    private void showPublishResult(String message, GraphObject result, FacebookRequestError error) {
        String title = null;
        String alertMessage = null;
        if (error == null) {
            title = getString(R.string.success);
         //   alertMessage = getString(R.string.successfully_posted_post, message);
            alertMessage = getString(R.string.successfully_posted_post);
        } else {
            title = getString(R.string.error);
            alertMessage = error.getErrorMessage();
        }

        Context context = this;
        
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        
        alertDialogBuilder.setTitle(title);
        
        alertDialogBuilder
                .setMessage(alertMessage)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
						
					}
				});
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
                
    }
    
    private void postPhoto() {
        if (hasPublishPermission()) {
        	int p = vp.getCurrentItem();
            Bitmap image = BitmapFactory.decodeResource(this.getResources(), pics.get(p));
            Request request = Request.newUploadPhotoRequest(Session.getActiveSession(), image, new Request.Callback() {
                @Override
                public void onCompleted(Response response) {
                    showPublishResult(getString(R.string.photo_post), response.getGraphObject(), response.getError());
                }
            });
            request.executeAsync();
        } else {
            pendingAction = PendingAction.POST_PHOTO;
        }
    }
    
    @SuppressWarnings("incomplete-switch")
    private void handlePendingAction() {
        PendingAction previouslyPendingAction = pendingAction;
        // These actions may re-set pendingAction if they are still pending, but we assume they
        // will succeed.
        pendingAction = PendingAction.NONE;

        switch (previouslyPendingAction) {
            case POST_PHOTO:
                postPhoto();
                break;
        }
    }
    
    private boolean hasPublishPermission() {
        Session session = Session.getActiveSession();
        return session != null && session.getPermissions().contains("publish_actions");
    }
    
    private void performPublish(PendingAction action) {
        Session session = Session.getActiveSession();

        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.supfunky.inspaquotes", 
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
                }
        } catch (NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }
        
        if (session != null && session.isOpened()) {
            pendingAction = action;
            if (hasPublishPermission()) {
                // We can do the action right away.
                handlePendingAction();
            } else {
                // We need to get new permissions, then complete the action when we get called back.
                session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSIONS));
                handlePendingAction();
            }
        } else {
            // start Facebook Login
            Session.openActiveSession(this, true, new Session.StatusCallback() {

              // callback when session changes state
              @Override
              public void call(Session session, SessionState state, Exception exception) {
            	  if(session.isClosed()) {
                	  logout();
                  }
              }
            });


        }
    }
    
    public void logout() {
    	Session session = Session.getActiveSession();
    	if(session != null && session.isOpened()) {
    		session.closeAndClearTokenInformation();
    		session.close();		
    	}
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    }


}
